package cn.edu.swu.wn.io;

import java.io.*;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;

public class ImageManager {

    private Map<String, String> imageMap;

    public ImageManager() {
        imageMap = new HashMap<>();
        // 确保images目录存在
        FileUtils.ensureDirectoryExists("images");
    }

    private String getFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        int queryIndex = url.lastIndexOf("?");
        if (queryIndex != -1) {
            url = url.substring(0, queryIndex);
        }

        // 提取最后一个"/"后的部分作为文件名
        int lastSlashIndex = url.lastIndexOf("/");
        if (lastSlashIndex != -1 && lastSlashIndex < url.length() - 1) {
            return url.substring(lastSlashIndex + 1);
        }

        return "";
    }

    public void listImages() {
        if (imageMap.isEmpty()) {
            System.out.println("暂无下载的图片");
            return;
        }

        System.out.println("已下载图片列表:");
        Set<String> imageNames = imageMap.keySet();
        int index = 1;
        for (String name : imageNames) {
            System.out.println(index + ". " + name + " -> " + imageMap.get(name));
            index++;
        }
    }

    public boolean downloadImage(String url) {
        try {
            String fileName = getFileNameFromUrl(url);
            if (fileName.isEmpty()) {
                System.out.println("无法从URL中提取文件名");
                return false;
            }

            if (imageMap.containsKey(fileName)) {
                System.out.println("图片已存在: " + fileName);
                return false;
            }
            String savePath = "images/" + fileName;
            FileUtils.saveImage(url, savePath);
            imageMap.put(fileName, savePath);

            FileUtils.appendLog("Downloaded: " + url + " -> " + savePath);

            System.out.println("图片下载成功: " + fileName);
            return true;
        } catch (IOException e) {
            System.out.println("下载失败: " + e.getMessage());
            return false;
        }
    }

    public void searchImage(String name) {
        boolean found = false;

        for (Map.Entry<String, String> entry : imageMap.entrySet()) {
            if (entry.getKey().contains(name)) {
                System.out.println("找到图片: " + entry.getKey() + " -> " + entry.getValue());
                found = true;
            }
        }

        if (!found) {
            System.out.println("未找到包含 \"" + name + "\" 的图片");
        }
    }

}
